package com.example.hxpc.guidancemanagement.fragment;


import android.content.Intent;
import android.os.Bundle;
        import android.support.annotation.Nullable;
        import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.hxpc.guidancemanagement.R;
import com.example.hxpc.guidancemanagement.activity.SendInformationActivity;
import com.example.hxpc.guidancemanagement.adapter.MyRecycleViewAdapter;
import com.example.hxpc.guidancemanagement.api.BaseApi;
import com.example.hxpc.guidancemanagement.base.ActivityInfo;
import com.example.hxpc.guidancemanagement.model.JsonBase;
import com.example.hxpc.guidancemanagement.model.JsonFeedback;
import com.example.hxpc.guidancemanagement.tools.LogoutT;
import com.example.hxpc.guidancemanagement.tools.SharePreferenceTools;
import com.example.hxpc.guidancemanagement.tools.ToastTools;
import com.example.hxpc.guidancemanagement.tools.dataTools.OkHttpTools;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tao on 2017/11/29.
 * 主页面-活动Frament
 */

public class MainActFragment extends Fragment implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener,BaseApi{
    private View rootView;
    private TextView te_foeget_pass , te_sure;
    private ImageView img_back , img_add;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private MyRecycleViewAdapter myRecycleViewAdapter;
    private List<ActivityInfo> aDatas = new ArrayList<>();
    private Intent intent;
    private ArrayList<String> listUrls = new ArrayList<>();
    private String content;
    private String time;
    private String photoUrl[];
    private long refreshTime = 0;//用来记录Fragment刷新的时间
    private OkHttpTools okHttpTools = new OkHttpTools();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null){
            rootView = inflater.inflate(R.layout.frament_main_activity,null);
        }
        refreshTime = 0;
        initView(rootView);
        return rootView;
    }

    //初始化控件
    public void initView(View rootView){
        aDatas.clear();
        img_add = (ImageView) rootView.findViewById(R.id.add_mark);
        if (SharePreferenceTools.getInstance(getActivity()).getString("flg").equals("4")){
            img_add.setVisibility(View.INVISIBLE);
        }else {
            img_add.setOnClickListener(this);
        }
        img_back = (ImageView) rootView.findViewById(R.id.back);
        img_back.setVisibility(View.GONE);
        te_foeget_pass = (TextView) rootView.findViewById(R.id.te_title);
        te_foeget_pass.setText("活动");
        te_sure = (TextView) rootView.findViewById(R.id.sure);
        te_sure.setVisibility(View.GONE);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.activity_recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.srl_re);
        swipeRefreshLayout.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setStackFromEnd(true);//列表在底部开始展开，反转后由上面开始展开
        layoutManager.setReverseLayout(true);//列表翻转
        recyclerView.setLayoutManager(layoutManager);

        myRecycleViewAdapter = new MyRecycleViewAdapter(getActivity(),aDatas,true);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        myRecycleViewAdapter.addFooterView(LayoutInflater.from(getActivity()).inflate(R.layout.recyclerview_headerview,null));
        recyclerView.setAdapter(myRecycleViewAdapter);
        myRecycleViewAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                ToastTools.toastMsg(getActivity(),"店家了");
            }

            @Override
            public void onItemLongOnClick(View view, int position) {
                ToastTools.toastMsg(getActivity(),"ooooooooo");
            }
        });
//        myRecycleViewAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
//            @Override
//            public void OnItemClick(View view, int position) {
//                switch (view.getId()){
//                    case R.id.activity_te_content:
//                        LogoutT.logout("点击了名字");
//                        LogoutT.logout("当前的位置是"+position);
//                        break;
//                }
//            }
//        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add_mark:
                intent = new Intent(getActivity(), SendInformationActivity.class);
                startActivityForResult(intent , 0);
                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser && isVisible()){
            if (refreshTime == 0 || (refreshTime != 0 && (System.currentTimeMillis() - refreshTime)>3*60*1000)){
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        LogoutT.logout(System.currentTimeMillis()+"  haomiao");
                        refreshTime = System.currentTimeMillis();
                        swipeRefreshLayout.setRefreshing(true);
                        LogoutT.logout("自动刷新");
                        okHttpTools.getActivityInformation(MainActFragment.this);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1){
            if (requestCode == 0){
                listUrls = data.getStringArrayListExtra("photo");
//                listUrls.clear();
//                photoUrl = data.getStringExtra("photo").split("&");
                content = data.getStringExtra("content");
                time = data.getStringExtra("publishTime");
//                LogoutT.logout(photoUrl.length+"  "+ photoUrl);
//                for (int i =0 ; i<photoUrl.length;i++){
//                    listUrls.add(photoUrl[i]);
//                    LogoutT.logout(photoUrl[i]);
//                }
                LogoutT.logout("oooo " + listUrls.size());
                LogoutT.logout("photo"+listUrls);
                LogoutT.logout("content"+content);
                if (listUrls.size() != 9){
                    listUrls.remove(listUrls.size()-1);
                }

                ActivityInfo info = new ActivityInfo(SharePreferenceTools.getInstance(getActivity()).getString("name"),content,data.getStringExtra("useHeadPhoto"),listUrls,time);
                aDatas.add(info);
                if (aDatas.size()>2){
                    myRecycleViewAdapter.addHeaderView(LayoutInflater.from(getActivity()).inflate(R.layout.recyclerview_footerview,null));
                }
                myRecycleViewAdapter.notifyDataSetChanged();
                recyclerView.smoothScrollToPosition(myRecycleViewAdapter.getItemCount()-1);
            }
        }
    }

    @Override
    public void onRefresh() {
//        myRecycleViewAdapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(true);
        LogoutT.logout("刷新");
        okHttpTools.getActivityInformation(MainActFragment.this);
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void backMsg(String success, JsonBase jsonBase) {

    }

    @Override
    public void backMsg(String success, JsonFeedback jsonFeedback) {
        if (success.equals("true")){
            aDatas.clear();
            for (int i = 0 ; i<jsonFeedback.getData().size() ; i++){
                ActivityInfo aIF = new ActivityInfo();
                aIF.setAvatar(jsonFeedback.getData().get(i).getUse_photo());
                aIF.setContent(jsonFeedback.getData().get(i).getContent());
                aIF.setName(jsonFeedback.getData().get(i).getName());
                aIF.setPublishTime(jsonFeedback.getData().get(i).getTime());
                aIF.setId(jsonFeedback.getData().get(i).getId());
                if (jsonFeedback.getData().get(i).getPhoto_path()!= null){
//                    LogoutT.logout("...... ...");
                    String[] path = jsonFeedback.getData().get(i).getPhoto_path().split("&");
//                    LogoutT.logout("...... ..." + path);
                    ArrayList<String> photoPath = new ArrayList<>();
                    for (int j = 0 ; j<path.length;j++){
                        photoPath.add(path[j]);
                        LogoutT.logout(".000   "+ path[j]);
                    }
                    aIF.setListUrls(photoPath);
                }
                aDatas.add(aIF);
            }
            myRecycleViewAdapter.notifyDataSetChanged();
            recyclerView.smoothScrollToPosition(myRecycleViewAdapter.getItemCount()-1);
        }else {
            myRecycleViewAdapter.notifyDataSetChanged();
            ToastTools.toastMsg(getActivity(),"没有动态");
        }
    }
}
